﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using WXY.Course.Model;

namespace WXY.Course.DAL
{
    public class CommentDAL
    {
        private static SqlHelper sqlHelper = new SqlHelper(ConfigurationManager.ConnectionStrings["CourseDB"].ConnectionString);

        public static CommentInfo Get(int code, bool isParent = false)
        {
            string sql = "select * from TComment where Code=@Code";

            SqlParameter parameter = new SqlParameter("@Code", code);

            return sqlHelper.ExecuteQuery(sql, CommandType.Text, (reader) =>
            {
                CommentInfo comment = null;
                while (reader.Read())
                {
                    comment = new CommentInfo();
                    comment.Code = Convert.ToInt32(reader["Code"]);
                    comment.CreateTime = Convert.ToDateTime(reader["CreateTime"]);
                    comment.Content = reader["Content"].ToString();
                    comment.Nick = reader["Nick"].ToString();
                    comment.IP = reader["IP"].ToString();
                    comment.Email = reader["Email"].ToString();
                    comment.QQ = reader["QQ"].ToString();
                    int pId = Convert.ToInt32(reader["PId"]);
                    comment.ParentCommentInfo = (pId == 0 || isParent) ? null : Get(pId, true);//只向上获取一级。
                }
                return comment;
            }, parameter);
        }

        public static IList<CommentInfo> GetList()
        {
            string sql = @"select * from TComment";

            return sqlHelper.ExecuteQuery(sql, CommandType.Text, (reader) =>
            {
                IList<CommentInfo> list = new List<CommentInfo>();
                while (reader.Read())
                {
                    CommentInfo comment = new CommentInfo();
                    comment.Code = Convert.ToInt32(reader["Code"]);
                    comment.CreateTime = Convert.ToDateTime(reader["CreateTime"]);
                    comment.Content = reader["Content"].ToString();
                    comment.Nick = reader["Nick"].ToString();
                    comment.IP = reader["IP"].ToString();
                    comment.Email = reader["Email"].ToString();
                    comment.QQ = reader["QQ"].ToString();
                    int pId = Convert.ToInt32(reader["PId"]);
                    comment.ParentCommentInfo = pId == 0 ? null : Get(pId, true);//只向上获取一级。
                    list.Add(comment);
                }
                return list;
            }, null);
        }

    }
}
